package vanhoc.android.mediakool;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


import org.blinkenlights.jid3.v2.POSSID3V2Frame;


import vanhoc.android.mediakool.R;
import vanhoc.android.mediakool.MediaPlayerService.PlayServiceBinder;
import vanhoc.android.mediakool.custom.adapter.DialogPlaylistAdapter;
import vanhoc.android.mediakool.custom.adapter.PlaylistAdapter;
import vanhoc.android.mediakool.db.DatabaseHelper;
import vanhoc.android.medialcool.helper.AlertDialogManager;
import vanhoc.android.medialcool.helper.SlidingPanel;
import vanhoc.android.medialcool.helper.TimeUtilities;
import vanhoc.android.medialcool.helper.ViewAnimation;
import vanhoc.android.medialcool.item.data.PlaylistItemData;
import vanhoc.android.medialcool.item.data.SongItemData;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.SlidingDrawer;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class MusicPlayerActivity extends Activity implements OnClickListener, SensorEventListener {
	

	DatabaseHelper databaseHelper = new DatabaseHelper(MusicPlayerActivity.this);
	
	/**
	 * Id cua bai hat dc chon de play
	 */
	private int _songIDPlay;
	
	/**
	 * fieldName :  ten truong nam trong songs table - cai ma se dua vao de lay ve ds se phat nhac (vd:  album  hoac artist hoac playlist ... hoac all)
	 *
	 */
	
	private String fieldName;
	
	
	/**
	 * Gia tri cua  fieldName
	 * Vd: album(fieldName) = mp3.zing.vn -> lay ve ds nhung bai hat nam trong mp3.zing.vn (dc gui tu AlbumActivity)
	 * vd: song(fieldName) = all  -> lay ve ds phat nhac la tat ca cac  bai hat co trogn sdcard (dc gui tu AllSOngsActivity)
	 */
	private String fieldValue;
	
	
	/**
	 * Bien cho biet co nghe toan bo ds bai hat lay ve theo flag hay khong?
	 */
	private Boolean isPlayAll;
	
	
	/**
	 * Bien cho biet co xao tron ds song lay ve hay khong? 
	 */
	private Boolean isShuffle;
	
	/**
	 * Du lieu cua bai hat hien tai dang dc phat
	 */
	public SongItemData currentSongData;
	
	/**
	 * danh sach cac playlist (khi user chon menu\add to playlist
	 */
	ArrayList<PlaylistItemData> arrPlaylist;
	
	/**
	 * dialog hien thi listview cac playlist da dc tao
	 */
	Dialog dialogPlaylist;
	
	//components
	public TextView txtSongTitle, txtSongArtist, txtSongDuration, txtSongCurrentDuration;
	private SeekBar songSeekbar;
	public ImageButton btnPrevious,btnRepeat, 
						btnShuffle,btnPlayPause,btnNext,
						btnCurrentListSong ;
	public ImageView songThumbnail;
	LinearLayout player_center;
	RelativeLayout player_center_bottom;
	ImageView artistThumb;
	
	
	/**
	 * browsing pick image for imageview
	 */
	private static int RESULT_LOAD_IMAGE = 1;
	
	/**
	 * Luu xem dang play hay pause
	 */
	Boolean isPlaying = true;
	
	
	Boolean isSeekbarHidden = false;
	
	
	public Handler handler = new Handler();
	
	
	HashMap<String, String> songPlayingData;
	
	
	//Object de lam viec voi lop MediaPlayerService 
	public MediaPlayerService mediaplayerService;
	
	
	public TimeUtilities ultis = new TimeUtilities();
	
	
	private int _songDuration;
	
	
	//bien luu tung do cua diem thu nhat, thu hai khi user vuot man hinh de chuyen bai hat
	int xFirstPosition , xSecondPosition;
	
	
	Boolean isBound;
	
	/**
	 * Luu id cua playlist dc chon de phat nhac (neu user click vao 1 bai hat thuoc 1 playlist nao do hoac click vao menu play all(shuffle) )
	 */
	int playlist_id = 0;
	
	
    /**
     * Animation
     */
	private Animation animShow, animHide;
	
	/**
	 * sensor manager
	 */
	private float mLastX, mLastY, mLastZ;
	private boolean isShake = false;
	private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private final float NOISE = (float) 2.0;
    private long lastUpdate;
	
    AlertDialogManager alertDialog = new AlertDialogManager();
	
    TelephonyManager telephonyManager;
    PhoneStateListener phoneStateListener;
    
    
    
    
    
    
    
	//service connection
	private ServiceConnection sc = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			/*ngắt kết nối thành công*/
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			/*kết nối thành công*/
			/*ép kiểu từ IBinder --> PlayServiceBinder*/
			PlayServiceBinder sHandle = (MediaPlayerService.PlayServiceBinder)service;
			
			/*gọi phương thức của PlayServiceBinder trả về chính service*/
			mediaplayerService = sHandle.getServiceHandle();
			
			//gui context sang ben MediaPlayerService
			mediaplayerService.setContext(MusicPlayerActivity.this);
			
			mediaplayerService._mediaController();
			
			MusicPlayerActivity.this.showCurrentSongInfo();
		}// End onServiceConnected
	};
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.music_player);
        //Lay ve cac view trong file xml
        initView();
        initPopup();
        
        //lay ve id cua bai hat
        this._getIntentData();
      		
  		this._startService();
  		
		//bindService
		this.doBindService();
		
		shakePlaySong();
    }


	/**
     * Lay ve cac du lieu tu cac activity khac gui qua thong qua intent
     * - Truoc tien la lay ve FLAG -> de biet dc la se play list song theo tieu chi nao (all hay theo 1 album hay theo 1 playlist hay theo 1 artist hay theo 1 genre nao do)
     * - Kiem tra xem o cac Activity kia, user co chon menu nao khong (phat toan bo hay xao chon bai).
     * 		+ Neu co thi lay ve danh sach nhac se choi theo tieu chi da chon, play bai hat dau tien trong ds do
     * 		+ Neu khong (tuc la user se chon 1 bai hat nao do tren ds nhac cua cac Activity kia, luc do ta lay ve id va choi bai nhac co id do
     */
	private void _getIntentData() {
		//lay ve tieu chi get list song
		this.fieldName	=	getIntent().getExtras().getString("FIELDNAME");
		
		this.fieldValue	=	getIntent().getExtras().getString("FIELDVALUE");
		
		this.playlist_id	=	getIntent().getExtras().getInt("PLAYLIST_ID");
		
		//lay ve gia tri cua chuc nang nghe toan bo
		this.isPlayAll	=	getIntent().getExtras().getBoolean("PLAYALL_FEATURE");
		
		//lay ve gia tri cua chuc nang xao tron ds nhac
		this.isShuffle	=	getIntent().getExtras().getBoolean("SHUFFLE_FEATURE");
		
		//neu gt cua isPlayAll va isShuffle deu la false thi co nghia user khong chon menu nao ma chon 1 bai hat tren list de choi bai hat do
		//lay ve id cua bai hat 
		if (isPlayAll == false && isShuffle == false) {
			this._songIDPlay	=	(Integer) getIntent().getExtras().get("songID");
		}
	}


	//start service va gui cac gia tri nhan dc qua intent sang sevice
	private void _startService() {
    	Intent itService = new Intent(MusicPlayerActivity.this, MediaPlayerService.class);
    	//gui tieu chi (fieldName va fieldValue) de sang service dua vao do de lay ve ds nhac tu csdl
    	itService.putExtra("FIELDNAME", this.fieldName);
    	itService.putExtra("FIELDVALUE", this.fieldValue);
    	
    	
    	//gui isPlayAll va isShuffle
    	itService.putExtra("PLAYALL_FEATURE", this.isPlayAll);
    	itService.putExtra("SHUFFLE_FEATURE", this.isShuffle);
    	
    	/*put pid */
		itService.putExtra("PLAYLIST_ID", this.playlist_id);
    	//neu gt cua isPlayAll va isShuffle deu la false thi moi gui id bai hat dc chon
		
    	if (isPlayAll == false && isShuffle == false) {
    		itService.putExtra("songID", this._songIDPlay);
		}
    	
		startService(itService);
	}

	//set hieu ung cho hinh ca si.Set onClick->an/hien phan seekbar..
    private void autoHidenArtistThumbnail() {
		//Neu khong click vao artistThumb(hinh nen ca si) thi player_center_bottom se tu dong an sau 1 khoang thoi gian
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				player_center_bottom.setVisibility(player_center_bottom.INVISIBLE);
				isSeekbarHidden = false;
			}
		}, 10000);
	}
    
    //onTouch event for seekbar
    private OnTouchListener seekbarOnTouchListener = new OnTouchListener() {
		
    	@Override
		public boolean onTouch(View v, MotionEvent event) {
			//send songSeekbar to Service
			mediaplayerService.setSeekbar(songSeekbar);
			seekChange(v);
			return false;
		}
	}; 
	
    private void initView() {
    	txtSongTitle 			= 	(TextView) findViewById(R.id.songTitle);
		txtSongArtist			=	(TextView) findViewById(R.id.songArtist);
		txtSongDuration			=	(TextView) findViewById(R.id.songDuration);
		txtSongCurrentDuration	=	(TextView) findViewById(R.id.songCurrentDuration);
		songSeekbar				=	(SeekBar) findViewById(R.id.songSeekbar);
		btnPrevious				=	(ImageButton) findViewById(R.id.btnPrevious);
		btnPlayPause			=	(ImageButton) findViewById(R.id.btnPlayPause);
		btnNext					=	(ImageButton) findViewById(R.id.btnNext);
		btnCurrentListSong		=	(ImageButton) findViewById(R.id.btnCurrentListSong);
		btnRepeat				=	(ImageButton) findViewById(R.id.btnRepeat);
		btnShuffle				=	(ImageButton) findViewById(R.id.btnShuffle);
		player_center			=	(LinearLayout) findViewById(R.id.player_center);
		player_center_bottom	=	(RelativeLayout) findViewById(R.id.player_center_bottom);
		artistThumb				=	(ImageView) findViewById(R.id.artistThumb);
		artistThumb.setOnTouchListener(ivArtistThumbnailOnTouch);
		autoHidenArtistThumbnail();
		
		
		/***********Cac xu ly khi click vao cac button ***********/
		btnPlayPause.setOnClickListener(this);
		btnNext.setOnClickListener(this);
		btnCurrentListSong.setOnClickListener(this);
		btnPrevious.setOnClickListener(this);
		btnRepeat.setOnClickListener(this);
		btnShuffle.setOnClickListener(this);
		//set onTouch for seekbar 
		songSeekbar.setOnTouchListener(seekbarOnTouchListener);
	}


	private void showArtistThumbnail(String thumbPath) {
		//SharedPreferences sp = getPreferences(MODE_PRIVATE);
		//String picturePath = sp.getString("picturePath", "");
		
		if (thumbPath.equals("") || thumbPath.equals(null)) { //chua co thumb
			//Len mang tai ve
			//Neu ket noi dc toi internet thi len mang tai
			
			//Neu khong ket noi dc thi set default
			artistThumb.setImageResource(R.drawable.artist_thumbnail);
		}else{//co duong dan hinh toi file anh
			//th1 : co duong dan toi file hinh va file hinh co ton tai -> tao dc bit map
			//th2 : co duong dan toi file hinh va file hinh kong ton tai -> khong tao dc bit map ->dat icon mac dinh
			Bitmap bm = BitmapFactory.decodeFile(thumbPath);
			if (bm != null) {
				artistThumb.setImageBitmap(BitmapFactory.decodeFile(thumbPath));
			}else{
				artistThumb.setImageResource(R.drawable.artist_thumbnail);
			}
		}
	}


	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	MenuInflater menuInflater = getMenuInflater();
    	menuInflater.inflate(R.menu.music_playler_menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
			case R.id.menu_change_thumb:
				//openLibrarySong();
				changeArtistThumbnail();
	            return true;
			case R.id.menu_repeate_playlist:
				mediaplayerService._repeatPlaylist();
	            return true;
			case R.id.menu_add_to_playlist:
				showDialogPlaylist();
	            return true;
			case R.id.menu_set_ringtone:
				shakeChange();
	            return true;
			case R.id.menu_setting:
	            return true;
			case R.id.menu_delete:
				confirmDeleteCurrentSong();
	            return true;
			default:
				return super.onOptionsItemSelected(item);
		}
    }
    

    private void openLibrarySong() {
    	Intent it = new Intent(getApplicationContext(), TabControlActivity.class);
		it.putExtra("tab", 1);
		it.putExtra("songPlayingID", MusicPlayerActivity.this._songIDPlay);
    	startActivity(it);
	}

	/**
     * Confirm 
     */
    public void confirmDeleteCurrentSong(){
    	AlertDialog alert = new AlertDialog.Builder(MusicPlayerActivity.this).create();
		alert.setTitle(getResources().getString(R.string.comfirm_delete_song));
		// Setting OK Button
		alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	deleteCurrentSong();
                }
        });
		
		alert.setButton2("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				
			}
		});
		
		alert.show();
    }
    
    
    
    /**
     * Xoa bai hat dang hat
     */
    private void deleteCurrentSong() {
		//xoa trong sdcard
    	deleteSongFromSdcard();
    	
    	//xoa trong csdl
    	deleteSongData();
    	
    	//chuyen sang choi bai ke tiep
    	playNextSong();
    	
    	scanMedia();
	}

    private void scanMedia() {
    	sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" +
        	    Environment.getExternalStorageDirectory())));
	}


	/**
     * Xoa du lieu 1 bai hat trong database
     */
	private void deleteSongData() {
		databaseHelper.openToWrite();
		databaseHelper.deleteSong(_songIDPlay);
		databaseHelper.close();
	}

	/**
	 * Xoa file mp3 tu trong sdcard
	 */
	private void deleteSongFromSdcard() {
		File mp3File = new File(currentSongData.getPath());
		if (mp3File.delete()) {
			Toast.makeText(getApplicationContext(), R.string.deleted_success, Toast.LENGTH_LONG).show();
		}else{
			Toast.makeText(getApplicationContext(), R.string.deleted_unsuccess, Toast.LENGTH_LONG).show();
		}
	}





	//Hien thi dialog danh sach cac playlist
    private void showDialogPlaylist() {
		dialogPlaylist = new Dialog(MusicPlayerActivity.this,0);
		dialogPlaylist.setContentView(R.layout.listview);
		dialogPlaylist.setTitle(getResources().getString(R.string.title_add_to_playlist));
		dialogPlaylist.show();
		
		//list view
		ListView lvPlaylist = (ListView) dialogPlaylist.findViewById(R.id.listView);
		
		//list playlist
		databaseHelper.openToRead();
		this.arrPlaylist = databaseHelper.getAllPlaylist();
    	databaseHelper.close();
		
    	//tao mới
    	this.arrPlaylist.add(new PlaylistItemData(0, getResources().getString(R.string.add_new)));
    	
		//adapter
    	DialogPlaylistAdapter pAdapter = new DialogPlaylistAdapter(getApplicationContext(), R.id.listView, arrPlaylist);
    	
    	lvPlaylist.setAdapter(pAdapter);
    	
    	lvPlaylist.setOnItemClickListener(playlistItemListener);
	}

    
    private OnItemClickListener playlistItemListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
			//neu chon tao moi
			if (arrPlaylist.get(position).getPlaylistId() == 0) {
				createPlaylist();
				//dialogPlaylist.dismiss();
			}else{ //nguoc lai them vao 1 playlist nao do da tao truoc do
				//lay ve cai id cua playlist da chon
				int pid = arrPlaylist.get(position).getPlaylistId();
				
				//co playlist id va song id ta insert vo song_playlist table
				int sid = mediaplayerService.getSongID();
				
				//kiem tra xem playlist co id la pid da chua bai hat nay (sid chua).Neu chua thi them.Neu co roi thi hien thi 1 cau thong bao
				databaseHelper.openToRead();
				ArrayList<Integer> listSongIdByPlaylist = databaseHelper.getSongListIdByPlaylist(pid);
				databaseHelper.close();
				
				if (listSongIdByPlaylist.contains(sid)){//neu bai hat nay truoc do da dc them vao playlist nay
					Toast.makeText(getApplicationContext(), R.string.existed_song_playlist, Toast.LENGTH_LONG).show();
				}else{
					addSongToPlaylist(sid, pid);
					Toast.makeText(getApplicationContext(), R.string.successfully, Toast.LENGTH_LONG).show();
				}
				dialogPlaylist.dismiss();
			}
		}
	};
	
  //tao moi 1 playlist
	protected void createPlaylist() {
		final Dialog dialogAddPlaylist = new Dialog(MusicPlayerActivity.this, 0);
		dialogAddPlaylist.setTitle(getResources().getString(R.string.add_new_playlist));
		dialogAddPlaylist.setContentView(R.layout.add_edit_title_layout);
		dialogAddPlaylist.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		dialogAddPlaylist.show();
		
		//lay ve cac thanh phan cua layout add_playlist_layout thogn qua dialogAddPlaylist
		final EditText txtPlaylistTitle 	= (EditText) dialogAddPlaylist.findViewById(R.id.txtTitle);
		final Button btnSave 				= (Button) dialogAddPlaylist.findViewById(R.id.btnSave);
		Button btnCancel 					= (Button) dialogAddPlaylist.findViewById(R.id.btnCancel);
		
		//set onclickListener for btnSave
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String playlistTitle = txtPlaylistTitle.getText().toString();
				if (playlistTitle.equals(null) || playlistTitle.equals("")) {
					alertDialog.showAlertDialog(MusicPlayerActivity.this, getString(R.string.error),
												getString(R.string.please_enter_playlist_title), false);
				}else{
					//kiem tra xem ten playlist user nhap vao da ton tai hay chua.neu chua moi cho tao
					if (checkPlaylistTitle(playlistTitle)) // neu co roi
						alertDialog.showAlertDialog(MusicPlayerActivity.this, getString(R.string.error),
													getString(R.string.existed_playlist_title), false);
					else// neu chua co
						addNewPlaylist(playlistTitle);
						dialogAddPlaylist.dismiss();
				}
				
			}
		});
		/*set onclickListener for btnSave*/
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialogAddPlaylist.dismiss();
			}
		});
	}
		
	
	/**
	 * Kiem tra xem 1 playlist title da ton tai trong bang playlists table chua
	 * @return
	 */
	public Boolean checkPlaylistTitle(String pTitle){
		for (int i = 0; i < arrPlaylist.size(); i++) {
			if (arrPlaylist.get(i).getPlaylistTitle().equals(pTitle)) {
				return true;
			}
		}
		
		return false;
	}
		
	
	
	
	protected void addNewPlaylist(String playlistTitle) {
		databaseHelper.openToWrite();
		//them 1 playlist moi vao playlist table
		databaseHelper.addPlaylist(playlistTitle);
		databaseHelper.close();
		
		//lay ve id cua playlist vua insert vao trong bang playlist table
		int pid = getNewPlaylistID();
		
		//co playlist id va song id ta insert vo song_playlist table
		addSongToPlaylist(mediaplayerService.getSongID(), pid);
		
		Toast.makeText(getApplicationContext(), R.string.successfully, Toast.LENGTH_LONG).show();
		dialogPlaylist.dismiss();
	}


	public void addSongToPlaylist(int sid, int pid){
		databaseHelper.openToWrite();
		databaseHelper.insertSongToPlaylist(sid, pid);
		databaseHelper.close();
	}
	
	// lay ve id playlist vua tao
	protected int getNewPlaylistID() {
			databaseHelper.openToRead();
			int pid = databaseHelper.getLastPlaylistId();
			databaseHelper.close();
			
			return pid;
	}


	//bind to service
    private void doBindService(){
    	// Establish a connection with the service.  We use an explicit
        // class name because there is no reason to be able to let other
        // applications replace our component.
    	 Intent pService = new Intent(getApplicationContext(), MediaPlayerService.class);
   		 bindService(pService, sc, BIND_AUTO_CREATE);
   		 isBound = true;
    }
    
    
   //Unbind to service
    private void doUnbindService(){
    	if (isBound) {
    		
		}
    }
   
 	//Xu ly cac su kien onclick khi click vao cac button
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btnPlayPause:
				handlePlayPauseMusic();
				break;
			case R.id.btnNext:
				playNextSong();
				break;
			case R.id.btnPrevious:
				playPreviousSong();
				break;
			case R.id.btnCurrentListSong:
				openCurrentListSong();
				break;
			case R.id.btnRepeat:
				repeatSong();
				break;
			case R.id.btnShuffle:
				shufflePlaylist();
				break;
			default:
				break;
		}
	}



	private void shufflePlaylist() {
		if (mediaplayerService.getStateShufflePlaylist() == true) {
			Toast.makeText(getApplicationContext(), R.string.shuffle_off, Toast.LENGTH_SHORT).show();
			btnShuffle.setImageResource(R.drawable.img_btn_shuffle);
			mediaplayerService.setStateShufflePlaylist(false); // ko tron
			//choi theo ds nhac lay dc ban dau khi chua tron (phuc hoi lai  ds nhac ban dau)
			mediaplayerService.restoreSongListID();
		}else{
			Toast.makeText(getApplicationContext(), R.string.shuffle_on, Toast.LENGTH_SHORT).show();
			btnShuffle.setImageResource(R.drawable.img_btn_shuffle_pressed);
			mediaplayerService.setStateShufflePlaylist(true);
			//tron lai ds nhac;
			mediaplayerService.shuffleSongListID();
		}
	}

	private void repeatSong() {
		if (mediaplayerService.getStateRepeateSong() == true) {
			Toast.makeText(getApplicationContext(),R.string.repeat_off, Toast.LENGTH_SHORT).show();
			btnRepeat.setImageResource(R.drawable.img_btn_repeat);
			mediaplayerService.setStateRepeatSong(false);
		}else{
			Toast.makeText(getApplicationContext(), R.string.repeat_on, Toast.LENGTH_SHORT).show();
			btnRepeat.setImageResource(R.drawable.img_btn_repeat_pressed);
			mediaplayerService.setStateRepeatSong(true);
		}
	}

	//Mo playlist chua bai hat dang hat o 1 activity khac
	private void openCurrentListSong() {
		Intent intent = new Intent(getApplicationContext(), SongListenningActivity.class);
		
		//gui tieu chi (fieldName va fieldValue) de sang service dua vao do de lay ve ds nhac tu csdl
		//Neu truoc do user chon phat nhac o playlist thi gui id playlist dang phat
		//Neu truoc do user chon phat nhac o tab all song thi hien thi het ds cac bai hat trong sdcard
		//Neu truoc do user chon phat nhac o 1 album (hoac 1 genre hoac 1 artist) thi gui flag tuong ung -> hien thi ds dang phat tuogn ung
		intent.putExtra("PLAYLIST_ID", this.playlist_id);
		intent.putExtra("FIELDNAME", this.fieldName);
		intent.putExtra("FIELDVALUE", this.fieldValue);
		intent.putExtra("songIdPlaying", mediaplayerService.getSongID());
		
		startActivity(intent);
	}

	
	private void playNextSong() {
		mediaplayerService._playNextSong();
		this.showCurrentSongInfo();
	}


	//Chay bai hat truoc do
	private void playPreviousSong() {
		mediaplayerService._playPreviousSong();
		this.showCurrentSongInfo();
	}


	//Xu ly khi bam vao nut play/pause
	private void handlePlayPauseMusic() {
		if (isPlaying == true) {
			pause();
			isPlaying	=	false;
		}else{
			//songSeekbar.setProgress(mediaplayerService.mediaPlayer.getCurrentPosition());
			play();
			isPlaying = true;
		}
	}
   
	
	//choi nhac
	private void play(){
		btnPlayPause.setImageResource(R.drawable.pause_36_icon);
		mediaplayerService._play();
	}
	
	//pause: Truoc do da bind toi service(service choi nhac da dc bat)
	private void pause() {
		btnPlayPause.setImageResource(R.drawable.play_36_icon);
		int currPos = mediaplayerService.mediaPlayer.getCurrentPosition();
		mediaplayerService._pause();
	}


	
	//Ham change seekbar khi nguoi dung keo thanh seekbar toi 1 vi tri nao do
    private void seekChange(View v) {
    	mediaplayerService._changeSeekbar(v);
	}
	
	public void showCurrentSongInfo(){
		this.currentSongData	=	mediaplayerService.getCurrentSong();
		
		txtSongTitle.setText(currentSongData.getName());
		txtSongArtist.setText(currentSongData.getArtist());
		
		//show total duration of song for TextView songDuration
		this._songDuration = mediaplayerService.getSongDuration();
		txtSongDuration.setText("" + ultis.milliSecondToTimer(this._songDuration));
		
		showArtistThumbnail(currentSongData.getThumbPath());
		
		//update seekbar
		MusicPlayerActivity.this.updateProgressBar();
		
		//
		if (mediaplayerService.mediaPlayer.isPlaying()) {
			btnPlayPause.setImageResource(R.drawable.pause_36_icon);
		}
	}

	
	/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
		//cứ 1 giây chạy 1 lần cập nhật seekbar va currenDuration
        handler.postDelayed(mUpdateTimeTask, 100);        
    }	
	
	
	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   int curPos = mediaplayerService.getCurrentSongDuration();
				songSeekbar.setProgress(curPos);
				
				//Hien thi thoi gian chay bai nhac theo seekbar(milliseconds)
				int millisecondDuration = mediaplayerService.getMilliSecondsCurrentDuration();
				txtSongCurrentDuration.setText("" + ultis.milliSecondToTimer(millisecondDuration));
				handler.postDelayed(this, 100);
		   }
	};
	
	
	//lay ve message tu ben service gui qua
	Handler msgHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			//cap nhat lại songID
			MusicPlayerActivity.this._songIDPlay = msg.arg1;
			MusicPlayerActivity.this.showCurrentSongInfo();
		};
	};
	
	
	@Override
	public void onBackPressed() {
		openLibrarySong();
	}
	
	
	//su kien onTouch cho ImageView hinh nghe si -> chuyen bai hat khi vuot man hinh
	private OnTouchListener ivArtistThumbnailOnTouch = new OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			DisplayMetrics display = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(display);
			//Lay ve kich thuoc cua man hinh
			int screenWidth = display.widthPixels;
			int screentHeight = display.heightPixels;
			//tung do cua tam diem cua man hinh
			int xCenter = screenWidth/2;
			
			int minSpace = 100;
			
			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					//an-hien phan player_center_bottom
					if (isSeekbarHidden) {
						player_center_bottom.setVisibility(v.INVISIBLE);
						isSeekbarHidden = false;
					}else{
						player_center_bottom.setVisibility(v.VISIBLE);
						isSeekbarHidden = true;
					}
					
					xFirstPosition = (int) event.getX();
				case MotionEvent.ACTION_UP:
					xSecondPosition	=	(int) event.getX();
			}
			
			int space = Math.abs(xSecondPosition - xFirstPosition);
			if (space >= minSpace) {
				if (xSecondPosition > xCenter && xCenter > xFirstPosition) {
					playPreviousSong();
					
					AlphaAnimation alpha = new AlphaAnimation(1, 0);
					alpha.setDuration(2000);
					artistThumb.startAnimation(alpha);
					animationArtistThumbnail();
				}
				if (xSecondPosition < xCenter && xCenter < xFirstPosition) {
					playNextSong();
					AlphaAnimation alpha = new AlphaAnimation(1, 0);
					alpha.setDuration(2000);
					artistThumb.startAnimation(alpha);
					animationArtistThumbnail();
				}
			}
			
			return true;
		}
	};


	protected void animationArtistThumbnail() {
		float centerX = (float) (artistThumb.getWidth()/2.0);
		float centerY = (float) (artistThumb.getHeight()/2.0);
		artistThumb.startAnimation(new ViewAnimation(centerX, centerY));
	}
	
	
	private void initPopup() {
    	
    	final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);

    	// Hide the popup initially.....
    	popup.setVisibility(View.INVISIBLE);
    	
    	animShow = AnimationUtils.loadAnimation( this, R.anim.popup_show);
    	animHide = AnimationUtils.loadAnimation( this, R.anim.popup_hide);
    	
    	final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
    	final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
    	showButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				popup.setVisibility(View.VISIBLE);
				popup.startAnimation( animShow );
				showButton.setEnabled(false);
				hideButton.setEnabled(true);
        }});
        
        hideButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				popup.startAnimation( animHide );
				showButton.setEnabled(true);
				hideButton.setEnabled(false);
				popup.setVisibility(View.GONE);
        }});

    	final TextView locationName = (TextView) findViewById(R.id.site_name);
        final TextView locationDescription = (TextView) findViewById(R.id.site_description);
        
        locationName.setText("CoderzHeaven");
        locationDescription.setText("Heaven of all working codes"
        							+ " A place where you can ask, share & even shout for code! Let�s share a wide range of technology here." +
        	  						" From this site you will get a lot of working examples in your favorite programming languages!." +
        	  						" Always remember we are only one comment away from you� Let�s shorten the distance between your doubts and your answers�");
        							
	}
	
	
	//set onClickListener cho hinh ca si
    private OnClickListener artisThumbListener = new OnClickListener() {
		
    	@Override
		public void onClick(View v) {
			if (isSeekbarHidden) {
				player_center_bottom.setVisibility(v.INVISIBLE);
				isSeekbarHidden = false;
			}else{
				player_center_bottom.setVisibility(v.VISIBLE);
				isSeekbarHidden = true;
			}
		}
	};
	
	public void updateThumbPath(String path){
		/*databaseHelper.openToRead();
		List<Integer> ids = getIds();
		for (int i = 0; i < ids.size(); i++) {
			Log.e("id item la", "" + ids.get(i));
			databaseHelper.updateArtistThumbnailPath(this._songIDPlay, path);
		}
		databaseHelper.close();*/
		
		databaseHelper.openToRead();
		databaseHelper.updateArtistThumbnailPath(currentSongData.getArtist(), path);
		databaseHelper.close();
	}
	
	
	
	public List<Integer> getIds(){
		List<Integer> ids = new ArrayList<Integer>();
		databaseHelper.openToRead();
		Cursor cursor = databaseHelper.getSongID(currentSongData.getArtist());
		cursor.moveToFirst();
		for (int i = 0; i < cursor.getCount(); i++) {
			ids.add(Integer.parseInt(cursor.getString(0)));
			cursor.moveToNext();
		}
		databaseHelper.close();
		return ids;
	}
	
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		//thay doi artist thumbnail
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };

			Cursor cursor = getContentResolver().query(selectedImage,
														filePathColumn, null, null, null);
			cursor.moveToFirst();

			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			cursor.close();
			
			updateThumbPath(picturePath);
			artistThumb.setImageBitmap(BitmapFactory.decodeFile(picturePath));
		}
	};
	
	private void changeArtistThumbnail(){
		Intent i = new Intent(
				Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(i, RESULT_LOAD_IMAGE);
	}

	
	private void shakeChange(){
		if (isShake) {
			isShake = false;
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.enable_shake), Toast.LENGTH_LONG).show();
		}else{
			isShake = true;
			Toast.makeText(getApplicationContext(), getResources().getString(R.string.disnable_shake), Toast.LENGTH_LONG).show();
		}
	}

	
	
	private void shakePlaySong() {
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        lastUpdate = System.currentTimeMillis();
	}

	
	@SuppressLint("NewApi")
	protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @SuppressLint("NewApi")
	protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
    }

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];
		if (!isShake) {
			mLastX = x;
			mLastY = y;
			mLastZ = z;
			return;
		}else {
			long actualTime = System.currentTimeMillis();
			float deltaX = Math.abs(mLastX - x); 
			float testX = mLastX - x;
			float deltaY = Math.abs(mLastY - y);
			float deltaZ = Math.abs(mLastZ - z);
			
			if (deltaX < NOISE) deltaX = (float)0.0;
			if (deltaY < NOISE) deltaY = (float)0.0;
			if (deltaZ < NOISE) deltaZ = (float)0.0;
			
			if ((actualTime - lastUpdate) < 100)  return;
			
			mLastX = x;
			mLastY = y;
			mLastZ = z;
			if (deltaX > deltaY) { //horizoncal
				if (testX < -10.0000 ) {
					playNextSong();
				}else if (testX > 10.0000 ) { 
					playPreviousSong();
				}
			}
     	}
	}
}
